package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"main/runJs"
	"net/url"
	"strings"
)

// generateSignature 用于生成 WebSocket 请求的签名
func (w *WebSocketApp) generateSignature(wss string) (string, error) {
	params := []string{"live_id", "aid", "version_code", "webcast_sdk_version", "room_id",
		"sub_room_id", "sub_channel_id", "did_rule", "user_unique_id", "device_platform", "device_type", "ac", "identity"}
	u, _ := url.Parse(wss)
	queryParams := u.Query()

	tplParams := []string{}
	for _, param := range params {
		tplParams = append(tplParams, fmt.Sprintf("%s=%s", param, queryParams.Get(param)))
	}
	param := strings.Join(tplParams, ",")

	md5Hasher := md5.New()
	md5Hasher.Write([]byte(param))
	md5Param := hex.EncodeToString(md5Hasher.Sum(nil))

	runJs.LoadGoja(w.UserAgent)
	output := runJs.ExecuteJS(md5Param)

	// 执行 sign.js 生成签名
	//cmd := exec.Command("node", "sign.js", fmt.Sprintf("{\"X-MS-STUB\": \"%s\"}", md5Param))
	//output, err := cmd.Output()
	//if err != nil {
	//	return "", fmt.Errorf("执行 sign.js 失败: %v", err)
	//}

	return output, nil
}
